package com.wang.lotterysystem.service.impl;

import com.wang.lotterysystem.controller.param.prize.CreatePrizeParam;
import com.wang.lotterysystem.controller.param.PageListParam;
import com.wang.lotterysystem.dao.dataobject.prize.PrizeDO;
import com.wang.lotterysystem.dao.mapper.PrizeMapper;
import com.wang.lotterysystem.service.PictureService;
import com.wang.lotterysystem.service.PrizeService;
import com.wang.lotterysystem.service.dto.PageListDTO;
import com.wang.lotterysystem.service.dto.prize.PrizeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
public class PrizeServiceImpl implements PrizeService {

    @Autowired
    private PictureService pictureService;

    @Autowired
    private PrizeMapper prizeMapper;

    @Override
    public Long createPrize(CreatePrizeParam prizeParam, MultipartFile file) {
        //创建一个PrizeDO对象并对其赋值
        PrizeDO prizeDO = new PrizeDO();
        prizeDO.setName(prizeParam.getPrizeName());
        prizeDO.setDescription(prizeParam.getDescription());
        prizeDO.setPrice(prizeParam.getPrice());

        String url = pictureService.savePicture(file);//返回保存图片之后的url
        prizeDO.setImageUrl(url); //设置奖品图片

        //将赋好值的PrizeDO对象插入数据库
        prizeMapper.insert(prizeDO);
        //返回id
        return prizeDO.getId();
    }

    @Override
    public PageListDTO<PrizeDTO> findPrizeList(PageListParam param) {

        //从数据库中查询指定页码的奖品列表
        List<PrizeDO> list = prizeMapper.queryPrizesByPage(param.offset(),param.getPageSize());
        //奖品列表中的奖品数目
        Integer total = prizeMapper.count();

        //
        PageListDTO<PrizeDTO> pageListDTO = new PageListDTO<>();
        //设置总条数
        pageListDTO.setTotal(total);

        List<PrizeDTO> prizeDTOS = new ArrayList<>();
        for (PrizeDO prizeDO : list) {
            PrizeDTO prizeDTO = new PrizeDTO();
            prizeDTO.setId(prizeDO.getId());
            prizeDTO.setName(prizeDO.getName());
            prizeDTO.setDescription(prizeDO.getDescription());
            prizeDTO.setPrice(prizeDO.getPrice());
            prizeDTO.setImageUrl(prizeDO.getImageUrl());
            prizeDTOS.add(prizeDTO);
        }

        pageListDTO.setRecords(prizeDTOS);

        return pageListDTO;
    }
}